<template>
  <div class="terms-page">
    <!-- 返回按钮 -->
    <button class="back-button" @click="handleBack">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="20"
        height="20"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round">
        <path d="M19 12H5M5 12l7 7 7-7" />
      </svg>
      <span>Back</span>
    </button>

    <div class="terms-container">
      <!-- 标题区域 -->
      <header class="terms-header">
        <h1>Terms and Conditions</h1>
        <p class="last-updated">Last Updated: October 30, 2025</p>
      </header>

      <!-- 主体内容区 -->
      <div class="terms-content">
        <!-- 左侧目录 -->
        <aside class="terms-sidebar">
          <nav class="toc">
            <ul>
              <li
                v-for="(item, index) in termsList"
                :key="index"
                :class="{ active: activeIndex === index }"
                @click="scrollToSection(index)"
                class="toc-item">
                <span class="toc-number">{{ index + 1 }}.</span>
                <span class="toc-title">{{ item.title }}</span>
              </li>
            </ul>
          </nav>
        </aside>

        <!-- 右侧内容 -->
        <main class="terms-main">
          <p class="intro">
            Welcome to Nexbie. These Terms and Conditions ("Terms") govern your access to and use of
            the Nexbie website, services, and applications (collectively, the "Service"), operated
            by Shenzhen NexusMake Technology Co., Ltd. Please read these Terms carefully.
          </p>

          <div class="sections-container" ref="sectionsContainer" @scroll="handleScroll">
            <section
              v-for="(item, index) in termsList"
              :key="index"
              :ref="(el) => (sectionRefs[index] = el)"
              class="term-section">
              <h2 class="section-heading">
                <span class="heading-number">{{ index + 1 }}.</span>
                {{ item.title }}
              </h2>
              <div class="section-body" v-html="item.content"></div>
            </section>
          </div>
        </main>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  const router = useRouter();

  // 条款数据（完整保留原文案）
  const termsList = ref([
    {
      title: 'Acceptance of Terms',
      content: `<p>By creating an account or using our Service, you agree to be bound by these Terms and our Privacy Policy. If you do not agree, you may not use the Service.</p>`,
    },
    {
      title: 'User Accounts',
      content: `
      <ul>
        <li><strong>Eligibility:</strong> You must be at least 18 years old to use Nexbie.</li>
        <li><strong>Account Security:</strong> We are committed to protecting your account and will implement reasonable and necessary security measures to maintain a secure environment. As the registered owner of the account, you agree that you are also responsible for safeguarding your account information. You are responsible for all activities that occur under your account and must notify us immediately of any unauthorized use.</li>
        <li><strong>Account Termination:</strong> You may delete your account at any time. We reserve the right to suspend or terminate your account if you violate these Terms or our Community Rules.</li>
      </ul>
    `,
    },
    {
      title: 'Content and Ownership',
      content: `
      <ul>
        <li><strong>Your Content:</strong> You retain all ownership rights to the original content you post or upload to Nexbie ("Your Content"). This includes text prompts, uploaded images, and 3D files.</li>
        <li><strong>AI-Generated Content:</strong> You own the AI-generated artwork you create using Nexbie's tools, subject to the rights of any underlying assets you used.</li>
        <li><strong>License to Nexbie:</strong> By posting content, you grant Nexbie a worldwide, non-exclusive, royalty-free license to use, reproduce, modify, display, and distribute your content in connection with operating and promoting the Service (e.g. posting your content on Nexbie's official social media or utilizing your content for onsite display). This license ends when you delete your content or your account.</li>
        <li><strong>Responsibility:</strong>
          <p>You are solely responsible for Your Content and ensuring you have the rights to authorize it and use it in accordance with this agreement and our policies. You agree not to post content that infringes on any third-party.</p>
          <p>You shall indemnify, defend, and hold us harmless against all claims that may be brought against us arising from any alleged infringement in connection with your use of our Services. You shall also compensate us for all losses, including but not limited to legal fees, attorney fees, and settlement amounts. If we receive any infringement claims, we may choose to take the following measures respectively or collectively:
            <ol type="a">
              <li>Immediately remove or disable access to the allegedly infringing content;</li>
              <li>Notify you of the claim and, where appropriate, forward the complaint to you;</li>
              <li>Withhold any earnings or revenue generated by or associated with the allegedly infringing content;</li>
              <li>Suspend your ability to post new content or access certain features;</li>
              <li>Suspend or terminate your account, particularly in cases of repeated infringement;</li>
              <li>Provide your information to the claimant as required by law or to facilitate a direct resolution of the dispute.</li>
            </ol>
          </p>
        </li>
      </ul>
    `,
    },
    {
      title: 'The "Nex" Feature',
      content: `
      <ul>
        <li><strong>Selection:</strong> Nexbie may, at its sole discretion, select user-generated content to be featured in a "Nex" campaign.</li>
        <li><strong>Campaigns:</strong> All Nex campaigns have a funding goal and a time limit. If successful, Nexbie will manage production and fulfillment. If it fails, all backers will be fully refunded under the crowdfunding system.</li>
        <li><strong>Revenue:</strong> If a Nex campaign you created is successful and the product is sold, you will earn a share of the revenue as detailed in your Payout Information settings or notified by the Nexbie team.</li>
        <li><strong>Refunds:</strong> If a successfully funded Nex product or a purchased store item is delivered and found to be significantly different from the product images, you are eligible to apply for a full refund.</li>
      </ul>
    `,
    },
    {
      title: 'Pro Accounts',
      content: `<p>Pro accounts are available via an application process and grant users access to advanced features, such as uploading their own design files. Pro accounts are subject to the same Terms and Community Rules.</p>`,
    },
    {
      title: 'Payments and Withdrawals',
      content: `
      <ul>
        <li><strong>Earnings:</strong> You may earn money through contest prizes and successful Nex campaigns. Your balance is displayed in your account or notified by the Nexbie team.</li>
        <li><strong>Withdrawals:</strong> You may request a withdrawal of your earnings. Payouts are processed via supported methods like PayPal or Zelle. You are responsible for any transaction fees and taxes.</li>
      </ul>
    `,
    },
    {
      title: 'Prohibited Conduct',
      content: `<p>You agree not to engage in any activity that is illegal, harmful, or violates our Community Rules or Public Content Policy.</p>`,
    },
    {
      title: 'Disclaimers and Limitation of Liability',
      content: `<p>The Service is provided "as is." Nexbie is not liable for any damages or losses arising from your use of the Service.</p>`,
    },
    {
      title: 'Governing Law and Dispute Resolution',
      content: `<p>These Terms shall be governed by the laws of the State of California, without regard to its conflict of law provisions. Any dispute, controversy, difference or claim arising out of or relating to the Agreement, including the existence, validity, interpretation, performance, breach or termination thereof or any dispute regarding any obligations arising out of or relating to it shall be referred to and finally resolved by arbitration administered by the Hong Kong International Arbitration Centre (HKIAC) under the HKIAC Arbitration Rules in force when the Notice of Arbitration is submitted. The seat of arbitration shall be Hong Kong. The arbitration language will be English. The arbitral award shall be final and binding upon both of the parties.</p>`,
    },
    {
      title: 'Changes to Terms',
      content: `<p>We may modify these Terms at any time. We will notify you of any changes by posting the new Terms on this page.</p>`,
    },
  ]);

  // 状态管理
  const activeIndex = ref(0);
  const sectionsContainer = ref<HTMLDivElement | null>(null);
  const sectionRefs = ref<any>([]);
  const scrollTimeout = ref<number | null>(null);

  // 修复的滚动到指定章节方法
  const scrollToSection = (index: number) => {
    // 简单直接的实现，确保兼容性和可靠性
    const container = sectionsContainer.value;
    const section = sectionRefs.value[index];

    if (container && section) {
      // 立即更新活动状态
      activeIndex.value = index;

      // 计算相对于容器的位置
      const containerRect = container.getBoundingClientRect();
      const sectionRect = section.getBoundingClientRect();
      const scrollPosition = sectionRect.top - containerRect.top + container.scrollTop - 20; // 20px偏移量

      // 使用原生滚动，确保兼容性
      container.scrollTo({
        top: scrollPosition,
        behavior: 'smooth',
      });
    }
  };

  // 处理滚动事件，更新当前活动章节
  const handleScroll = () => {
    // 防抖处理，提高性能
    if (scrollTimeout.value) {
      window.clearTimeout(scrollTimeout.value);
    }

    scrollTimeout.value = window.setTimeout(() => {
      if (!sectionsContainer.value) return;

      const container = sectionsContainer.value;
      const scrollTop = container.scrollTop;
      const viewportHeight = container.clientHeight;

      // 遍历所有章节，找到当前可见的章节
      for (let i = 0; i < sectionRefs.value.length; i++) {
        const section = sectionRefs.value[i];
        if (!section) continue;

        const sectionTop = section.offsetTop;
        const sectionHeight = section.offsetHeight;

        // 检查章节是否在可视区域内
        if (sectionTop <= scrollTop + 50 && sectionTop + sectionHeight > scrollTop) {
          activeIndex.value = i;
          break;
        }
      }
    }, 100);
  };

  // 返回按钮处理
  const handleBack = () => {
    console.log('返回上一页');
    // 实际应用中使用路由返回
    router.back();
  };

  // 初始化
  onMounted(() => {
    nextTick(() => {
      // 确保DOM加载完成后初始化
      handleScroll();
    });
  });
</script>

<style scoped>
  .terms-page {
    min-height: 100vh;
    background-color: #f9f9f9;
    padding: 20px;
    box-sizing: border-box;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    position: relative;
  }

  /* 返回按钮 */
  .back-button {
    display: flex;
    align-items: center;
    gap: 8px;
    background: transparent;
    border: none;
    color: #f76b1b;
    font-size: 14px;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 6px;
    transition: all 0.2s ease;
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 10;
  }

  .back-button:hover {
    background-color: rgba(247, 107, 27, 0.1);
  }

  .terms-container {
    max-width: 1400px;
    margin: 0 auto;
    padding-top: 40px;
  }

  /* 标题区域 */
  .terms-header {
    text-align: center;
    margin-bottom: 30px;
    padding: 0 20px;
  }

  .terms-header h1 {
    color: #f76b1b;
    font-size: 28px;
    margin-bottom: 12px;
  }

  .last-updated {
    color: #666;
    font-size: 14px;
  }

  /* 主体内容区布局 */
  .terms-content {
    display: flex;
    gap: 30px;
    height: calc(100vh - 200px);
    min-height: 500px;
  }

  /* 左侧目录 - 确保可点击区域完整 */
  .terms-sidebar {
    width: 300px;
    flex-shrink: 0;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }

  .toc {
    height: 100%;
    overflow-y: auto;
    padding: 10px 0;
  }

  .toc ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .toc-item {
    padding: 12px 20px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: flex-start;
    color: #333;
    font-size: 14px;
    border-left: 3px solid transparent;
    user-select: none; /* 防止文本选中干扰点击 */
    width: 100%;
    box-sizing: border-box;
  }

  .toc-item:hover {
    background-color: rgba(247, 107, 27, 0.05);
    padding-left: 22px;
  }

  .toc-item.active {
    background-color: rgba(247, 107, 27, 0.1);
    border-left-color: #f76b1b;
    color: #f76b1b;
    font-weight: 500;
  }

  .toc-number {
    font-weight: 600;
    margin-right: 8px;
    min-width: 20px;
  }

  .toc-title {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* 右侧内容区 */
  .terms-main {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .intro {
    color: #333;
    line-height: 1.6;
    margin-bottom: 24px;
    font-size: 15px;
  }

  .sections-container {
    flex: 1;
    overflow-y: auto;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    padding: 30px 40px;
    line-height: 1.8;
  }

  .term-section {
    margin-bottom: 40px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;
  }

  .term-section:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
  }

  .section-heading {
    color: #222;
    font-size: 20px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
  }

  .heading-number {
    color: #f76b1b;
    font-weight: 700;
    margin-right: 10px;
  }

  .section-body {
    color: #444;
    font-size: 15px;
  }

  .section-body ul,
  .section-body ol {
    margin: 16px 0;
    padding-left: 24px;
  }

  .section-body li {
    margin-bottom: 8px;
  }

  .section-body strong {
    color: #f76b1b;
  }

  /* 响应式适配 */
  @media (max-width: 1024px) {
    .terms-content {
      flex-direction: column;
      height: auto;
      gap: 20px;
    }

    .terms-sidebar {
      width: 100%;
      max-height: 200px;
    }

    .sections-container {
      padding: 20px;
      max-height: 600px;
    }
  }

  @media (max-width: 768px) {
    .terms-header h1 {
      font-size: 24px;
    }

    .toc-item {
      padding: 10px 15px;
      font-size: 13px;
    }

    .section-heading {
      font-size: 18px;
    }
  }
</style>
